<template>
  <div class="user-group-page">
    <div class="stats-grid">
      <div v-for="(stat, key) in statistics.by_category" :key="key" class="stat-card">
        <div class="stat-icon">👥</div>
        <div class="stat-info">
          <div class="stat-label">{{ stat.name }}</div>
          <div class="stat-value">{{ stat.group_count }} 个组</div>
          <div class="stat-desc">{{ stat.user_count }} 名用户</div>
        </div>
      </div>
    </div>

    <div class="main-card">
      <div class="card-header">
        <h2>📋 用户组管理</h2>
        <div class="header-actions">
          <select v-model="categoryFilter" class="filter-select">
            <option value="">全部分类</option>
            <option value="test">测试部</option>
            <option value="development">开发部</option>
            <option value="production">生产部</option>
            <option value="leadership">部门领导</option>
            <option value="other">其他</option>
          </select>
          <button @click="openAddModal" class="btn btn-primary">+ 新建用户组</button>
        </div>
      </div>

      <table class="data-table">
        <thead>
          <tr>
            <th>组名</th>
            <th>分类</th>
            <th>用户数量</th>
            <th>描述</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="group in filteredGroups" :key="group.id">
            <td><strong>{{ group.name }}</strong></td>
            <td><span class="category-badge" :class="'cat-' + group.category">{{ group.category_display }}</span></td>
            <td><span class="user-count">{{ group.user_count || 0 }} 人</span></td>
            <td>{{ group.description || '-' }}</td>
            <td>{{ formatDate(group.created_at) }}</td>
            <td>
              <button @click="openEditModal(group)" class="btn-sm">编辑</button>
              <button @click="manageUsers(group)" class="btn-sm btn-info">管理用户</button>
              <button @click="deleteGroup(group.id)" class="btn-sm btn-danger">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <h3>{{ isEdit ? '编辑用户组' : '新建用户组' }}</h3>
        <form @submit.prevent="saveGroup">
          <div class="form-group">
            <label>组名 *</label>
            <input v-model="formData.name" required />
          </div>
          <div class="form-group">
            <label>分类 *</label>
            <select v-model="formData.category" required>
              <option value="test">测试部</option>
              <option value="development">开发部</option>
              <option value="production">生产部</option>
              <option value="leadership">部门领导</option>
              <option value="other">其他</option>
            </select>
          </div>
          <div class="form-group">
            <label>描述</label>
            <textarea v-model="formData.description" rows="3"></textarea>
          </div>
          <div class="form-actions">
            <button type="submit" class="btn btn-primary">保存</button>
            <button type="button" @click="closeModal" class="btn">取消</button>
          </div>
        </form>
      </div>
    </div>

    <div v-if="showUserModal" class="modal-overlay" @click="closeUserModal">
      <div class="modal-content large" @click.stop>
        <h3>管理用户 - {{ currentGroup.name }}</h3>
        <div v-if="allUsers.length === 0" class="empty-message">
          没有可用的用户
        </div>
        <div v-else class="user-list">
          <div v-for="user in allUsers" :key="user.id" class="user-item">
            <input type="checkbox" :value="user.id" v-model="selectedUsers" />
            <span>{{ user.username }}</span>
            <span class="user-email">{{ user.email }}</span>
          </div>
        </div>
        <div class="selected-info">
          已选择: {{ selectedUsers.length }} 个用户
        </div>
        <div class="form-actions">
          <button @click="updateGroupUsers" class="btn btn-primary">保存</button>
          <button @click="closeUserModal" class="btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import api from '../services/api'

const groups = ref([])
const statistics = ref({ by_category: {} })
const allUsers = ref([])
const categoryFilter = ref('')
const showModal = ref(false)
const showUserModal = ref(false)
const isEdit = ref(false)
const currentGroup = ref({})
const selectedUsers = ref([])
const formData = ref({
  name: '',
  category: 'other',
  description: ''
})

const filteredGroups = computed(() => {
  if (!categoryFilter.value) return groups.value
  return groups.value.filter(g => g.category === categoryFilter.value)
})

const loadData = async () => {
  try {
    console.log('开始加载数据...')
    const [groupsData, statsData, usersData] = await Promise.all([
      api.getUserGroups(),
      api.getUserGroupStatistics(),
      api.getAllUsers()
    ])
    console.log('获取到的组数据:', groupsData)
    console.log('获取到的统计数据:', statsData)
    console.log('获取到的用户数据:', usersData)
    
    groups.value = Array.isArray(groupsData) ? groupsData : (groupsData.results || [])
    statistics.value = statsData
    allUsers.value = Array.isArray(usersData) ? usersData : (usersData.results || [])
    
    console.log('用户列表:', allUsers.value)
  } catch (error) {
    console.error('加载失败:', error)
    alert('加载数据失败: ' + (error.message || '未知错误'))
  }
}

const openAddModal = () => {
  isEdit.value = false
  formData.value = { name: '', category: 'other', description: '' }
  showModal.value = true
}

const openEditModal = (group) => {
  isEdit.value = true
  formData.value = { ...group }
  showModal.value = true
}

const closeModal = () => {
  showModal.value = false
}

const saveGroup = async () => {
  try {
    console.log('提交的数据:', formData.value)
    if (isEdit.value) {
      await api.updateUserGroup(formData.value.id, formData.value)
      console.log('更新成功')
    } else {
      const result = await api.createUserGroup(formData.value)
      console.log('创建成功:', result)
    }
    closeModal()
    loadData()
  } catch (error) {
    console.error('保存失败:', error)
    const errorMsg = error.response?.data?.error || error.response?.data?.detail || error.message
    alert('保存失败: ' + errorMsg)
  }
}

const deleteGroup = async (id) => {
  if (!confirm('确定删除此用户组吗？')) return
  try {
    await api.deleteUserGroup(id)
    loadData()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

const manageUsers = (group) => {
  console.log('管理用户 - 当前组:', group)
  currentGroup.value = group
  // 如果group.users是ID数组，直接使用；否则提取ID
  if (group.users && group.users.length > 0) {
    if (typeof group.users[0] === 'number') {
      selectedUsers.value = [...group.users]
    } else if (typeof group.users[0] === 'object') {
      selectedUsers.value = group.users.map(u => u.id || u)
    } else {
      selectedUsers.value = []
    }
  } else {
    selectedUsers.value = []
  }
  console.log('初始选中的用户ID:', selectedUsers.value)
  console.log('可选用户列表:', allUsers.value)
  showUserModal.value = true
}

const closeUserModal = () => {
  showUserModal.value = false
}

const updateGroupUsers = async () => {
  try {
    console.log('当前组:', currentGroup.value)
    console.log('选中的用户:', selectedUsers.value)
    
    const updateData = {
      name: currentGroup.value.name,
      category: currentGroup.value.category,
      description: currentGroup.value.description || '',
      user_ids: selectedUsers.value
    }
    console.log('提交数据:', updateData)
    
    await api.updateUserGroup(currentGroup.value.id, updateData)
    console.log('更新成功')
    closeUserModal()
    loadData()
  } catch (error) {
    console.error('更新失败:', error)
    const errorMsg = error.response?.data?.error || error.response?.data?.detail || error.message
    alert('更新失败: ' + errorMsg)
  }
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.user-group-page { padding: 20px; }
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 30px; }
.stat-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 20px; border-radius: 12px; color: white; display: flex; gap: 15px; align-items: center; }
.stat-icon { font-size: 36px; }
.stat-value { font-size: 24px; font-weight: bold; }
.main-card { background: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.card-header { padding: 20px; border-bottom: 1px solid #eee; display: flex; justify-content: space-between; align-items: center; }
.header-actions { display: flex; gap: 10px; }
.filter-select { padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; }
.data-table { width: 100%; border-collapse: collapse; }
.data-table th, .data-table td { padding: 12px; text-align: left; border-bottom: 1px solid #eee; }
.category-badge { padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 600; }
.cat-test { background: #e3f2fd; color: #1976d2; }
.cat-development { background: #f3e5f5; color: #7b1fa2; }
.cat-production { background: #ffebee; color: #c62828; }
.cat-leadership { background: #fff3e0; color: #e65100; }
.cat-other { background: #f5f5f5; color: #616161; }
.user-count { font-weight: 600; color: #667eea; }
.btn-sm { padding: 4px 8px; font-size: 12px; margin-right: 5px; border: none; border-radius: 4px; cursor: pointer; }
.btn-info { background: #2196f3; color: white; }
.btn-danger { background: #f44336; color: white; }
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.modal-content { background: white; padding: 24px; border-radius: 8px; min-width: 500px; max-height: 80vh; overflow-y: auto; }
.modal-content.large { min-width: 600px; }
.form-group { margin-bottom: 16px; }
.form-group label { display: block; margin-bottom: 6px; font-weight: 600; }
.form-group input, .form-group select, .form-group textarea { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
.form-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px; }
.btn { padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; }
.btn-primary { background: #667eea; color: white; }
.user-list { max-height: 400px; overflow-y: auto; border: 1px solid #eee; border-radius: 4px; padding: 10px; margin-bottom: 10px; }
.user-item { padding: 8px; display: flex; align-items: center; gap: 10px; }
.user-item:hover { background: #f5f5f5; }
.user-email { color: #999; font-size: 12px; margin-left: auto; }
.selected-info { padding: 10px; background: #e3f2fd; border-radius: 4px; color: #1976d2; font-weight: 600; margin-bottom: 10px; }
.empty-message { padding: 20px; text-align: center; color: #999; }
</style>
